package com.qk.management.service.serviceimpl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.DeptException;
import com.qk.entity.Dept;
import com.qk.management.mapper.DeptMapper;
import com.qk.management.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


/**
 * @author 上官徵羽
 * @version 1.0
 * @since 2025-09-29 11:13
 */
@Service
@SuppressWarnings("all")
public class DeptServiceImpl implements DeptService {
    @Override
    public void updateById(Dept dept) {
        judgeRepetition(dept.getName(), dept.getId());
        LocalDateTime now = LocalDateTime.now();
        dept.setUpdateTime(now);
        deptMapper.update(dept);
    }

    @Override
    public List<Dept> listAll() {
        return deptMapper.listAll();
    }

    @Override
    public Dept getById(Integer id) {
        Dept dept = deptMapper.getById(id);
        return dept;
    }

    @Autowired
    private DeptMapper deptMapper;

    @Override
    public void delete(Integer id) {
        deptMapper.delete(id);
    }

    @Override
    public PageResult<Dept> page(String name, Integer status, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Dept> list = deptMapper.page(name, status);
        Page<Dept> dept = (Page<Dept>) list;
        return PageResult.<Dept>builder()
                .total(Long.parseLong(dept.getTotal() + ""))
                .rows(deptMapper.page(name, status))
                .build();
    }

    @Override
    public void addDept(Dept dept) {
        judgeRepetition(dept.getName(), null);
        LocalDateTime now = LocalDateTime.now();
        dept.setCreateTime(now);
        dept.setUpdateTime(now);
        deptMapper.addDept(dept);
    }

    private void judgeRepetition(String name,Integer id) {
        Dept dept = deptMapper.getByName(name);
        if (!ObjectUtil.equals(dept.getId(),id)&&!ObjectUtil.isEmpty(dept)) {
            DeptException.throwDeptException(ParamEnum.DEPARTMENT_NAME_ALREADY_EXISTS);
        }
    }
}
